package com.pig.rpc.transmission.socket.server;

import com.pig.rpc.dto.RpcReq;
import com.pig.rpc.dto.RpcResp;
import com.pig.rpc.handler.RpcReqHandler;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

@Slf4j
@AllArgsConstructor
public class SocketReqHandler implements Runnable{
    private final Socket socket;
    private final RpcReqHandler rpcReqHandler;

    @SneakyThrows
    @Override
    public void run() {
        ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
        RpcReq rpcReq = (RpcReq)inputStream.readObject();


        //假装调用了rpcReq中的接口实现类的方法
        //Object data = invoke(rpcReq);
        Object data = rpcReqHandler.invoke(rpcReq);


        ObjectOutputStream outputStream = new ObjectOutputStream(socket
                .getOutputStream());
        RpcResp<?> rpcResp = RpcResp.success(rpcReq.getReqId(), data); // ?可以放任意类型数据进去
        outputStream.writeObject(rpcResp);
        outputStream.flush();
    }
}
